<template>
  <div class="message-center">
    <!-- 左侧对话列表 -->
    <aside class="conversation-sidebar">
      <div class="sidebar-header">
        <div class="header-title">
          <button @click="goBack" class="back-btn-icon" title="返回">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5M12 19l-7-7 7-7"/>
            </svg>
          </button>
          <svg class="title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
          </svg>
          <h2>消息中心</h2>
        </div>
        <div class="search-box">
          <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="11" cy="11" r="8"></circle>
            <path d="m21 21-4.35-4.35"></path>
          </svg>
          <input v-model="keyword" type="text" placeholder="搜索对话..." @input="filterConvs" />
                </div>
      </div>
      
      <div class="conversation-list" v-if="!loading">
        <div v-if="filteredConvs.length === 0" class="empty-state">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
          </svg>
          <p>暂无对话</p>
        </div>
        <button 
          v-for="c in filteredConvs" 
          :key="c.id" 
          class="conversation-item" 
          :class="{ active: current?.id === c.id }"
          @click="selectConv(c)"
        >
          <div class="avatar-wrapper">
            <img :src="c.avatar" alt="avatar" class="avatar" />
            <span v-if="c.unreadCount > 0" class="online-badge"></span>
          </div>
          <div class="conversation-info">
            <div class="info-header">
              <span class="contact-name">{{ c.name }}</span>
              <span class="message-time">{{ formatTime(c.lastMessageTime) }}</span>
            </div>
            <div class="info-footer">
              <span class="last-message" :class="{ unread: c.unreadCount > 0 }">
                {{ c.lastMessage || '暂无消息' }}
              </span>
              <span v-if="c.unreadCount > 0" class="unread-badge">
                {{ c.unreadCount > 99 ? '99+' : c.unreadCount }}
              </span>
              </div>
            </div>
          </button>
      </div>
      <div v-else class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
    </aside>

    <!-- 右侧聊天区域 -->
    <section class="chat-area">
      <div v-if="!current" class="welcome-screen">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
          <path d="M9 10h.01M15 10h.01"></path>
        </svg>
        <h3>欢迎使用消息中心</h3>
        <p>选择一个对话开始聊天</p>
      </div>
      
      <div v-else class="chat-container">
        <!-- 聊天头部 -->
        <header class="chat-header">
          <div class="header-left">
            <div class="avatar-wrapper">
              <img :src="current.avatar" alt="avatar" class="avatar" />
              <span class="status-dot" :class="{ online: connStatus === 'connected' }"></span>
            </div>
            <div class="contact-details">
              <h3 class="contact-name">{{ current.name }}</h3>
              <div class="contact-status">
                <span class="connection-text" :class="statusClass">{{ connStatusText }}</span>
                <span v-if="current.productTitle" class="product-tag">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                    <path d="M3 9h18M9 21V9"></path>
                  </svg>
                  {{ current.productTitle }}
                </span>
              </div>
            </div>
          </div>
          <div class="header-actions">
            <button class="icon-btn" @click="clearUnread" title="标记已读">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="20 6 9 17 4 12"></polyline>
              </svg>
            </button>
            <button class="icon-btn" @click="refreshMessages" title="刷新">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"></path>
              </svg>
            </button>
          </div>
        </header>

        <!-- 消息列表 -->
        <main class="messages-container" ref="msgsRef">
          <div v-for="m in msgs" :key="m.id" class="message-wrapper" :class="{ own: m.senderId === me }">
            <!-- 对方消息：头像在左 -->
            <template v-if="m.senderId !== me">
              <div class="message-avatar">
              <img :src="m.senderAvatar" alt="avatar" />
            </div>
              <div class="message-group">
                <div class="message-bubble" :class="{ unread: m.isUnread }">
                  <template v-if="m.type === 'text'">{{ m.content }}</template>
                  <template v-else-if="m.type === 'image'">
                    <img class="message-image" :src="m.content" alt="图片" />
                  </template>
                <template v-else>{{ m.content }}</template>
                </div>
                <div class="message-info">
                  <span class="message-time">{{ formatTime(m.createdAt) }}</span>
                </div>
              </div>
            </template>
            
            <!-- 自己消息：头像在右 -->
            <template v-else>
              <div class="message-group">
                <div class="message-bubble">
                  <template v-if="m.type === 'text'">{{ m.content }}</template>
                  <template v-else-if="m.type === 'image'">
                    <img class="message-image" :src="m.content" alt="图片" />
                  </template>
                  <template v-else>{{ m.content }}</template>
                </div>
                <div class="message-info">
                  <span class="message-time">{{ formatTime(m.createdAt) }}</span>
                  <span class="read-status" :class="getReadStatusClass(m)">
                  {{ getReadStatusText(m) }}
                </span>
              </div>
            </div>
              <div class="message-avatar">
              <img :src="getUserAvatar() || '/logo.jpg'" alt="avatar" />
            </div>
            </template>
          </div>
        </main>

        <!-- 输入区域 -->
        <footer class="input-area">
          <div class="input-wrapper">
            <textarea 
              v-model="draft" 
              rows="1" 
              placeholder="输入消息...按 Enter 发送"
              @keydown.enter.exact.prevent="send"
              @input="autoResize"
              ref="textareaRef"
            />
            <button class="send-btn" :disabled="!canSend" @click="send">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
              <span>发送</span>
            </button>
          </div>
        </footer>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get, post, put } from '../api/request'
import messageService from '../services/messageService'
import { useSmartNavigation } from '../utils/navigation'
import { getImageUrl } from '../utils/imageUtils'

const route = useRoute()
const router = useRouter()
const { goBack } = useSmartNavigation()

const loading = ref(false)
const convs = ref([])
const filteredConvs = ref([])
const keyword = ref('')
const current = ref(null)
const msgs = ref([])
const draft = ref('')
const me = Number(localStorage.getItem('userId') || '0')
const msgsRef = ref(null)
const textareaRef = ref(null)

const connStatus = ref('disconnected')
const connStatusText = computed(() => connStatus.value==='connected' ? '🟢 实时连接' : (connStatus.value==='polling' ? '🟡 轮询模式' : '🔴 连接断开'))
const statusClass = computed(() => ({connected: connStatus.value==='connected'}))

const canSend = computed(() => !!current.value && !!draft.value.trim())

const getUserAvatar = () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    return getImageUrl(userInfo.avatar) || '/logo.jpg'
  } catch {
    return '/logo.jpg'
  }
}

const formatTime = (t) => {
  if (!t) return ''
  const d = new Date(t)
  return `${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`
}

const mapConv = (c) => ({
  id: c.contactUserId,
  name: c.contactNickname || c.contactUsername || `用户${c.contactUserId}`,
  avatar: getImageUrl(c.contactAvatar) || '/logo.jpg',
  lastMessage: c.lastMessageContent,
  lastMessageTime: c.lastMessageTime,
  unreadCount: c.unreadCount || 0,
  productId: c.productId,
  productTitle: c.productTitle,
  productImage: c.productImage
})

const mapMsg = (m) => ({
  id: m.id,
  senderId: m.senderId || m.fromUserId,
  receiverId: m.receiverId || m.toUserId,
  content: m.content,
  type: (m.typeText ? String(m.typeText).toLowerCase() : (m.type===2?'image':'text')),
  createdAt: m.createdAt || m.createTime,
  isRead: m.isRead,
  isUnread: m.isUnread !== undefined ? m.isUnread : (m.isRead === 0),
  readStatus: m.readStatus,
  readTime: m.readTime,
  senderAvatar: getImageUrl(m.senderAvatar || m.fromAvatar) || '/logo.jpg'
})

const loadConvs = async () => {
  loading.value = true
  try {
    const res = await get('/messages/conversations')
    const list = Array.isArray(res?.data) ? res.data : []
    convs.value = list.map(mapConv)
    filterConvs()
  } catch (e) { console.error(e) } finally { loading.value=false }
}

const filterConvs = () => {
  const k = keyword.value.trim().toLowerCase()
  filteredConvs.value = k ? convs.value.filter(c => (c.name||'').toLowerCase().includes(k)) : [...convs.value]
}

const loadMsgs = async (uid) => {
  try {
    const res = await get(`/messages/conversation/${uid}`)
    const list = Array.isArray(res?.data) ? res.data : []
    msgs.value = list.map(mapMsg)
    await nextTick(); scrollToBottom()
  } catch (e) { console.error(e) }
}

const selectConv = async (c) => {
  current.value = c
  await loadMsgs(c.id)
  if ((c.unreadCount||0)>0) { await markConvRead(c.id); c.unreadCount=0 }
}

// 从商品详情进入：根据路由参数初始化会话
const initByRoute = async () => {
  const q = route.query || {}
  const to = q.to ? Number(q.to) : null
  if (!to || !Number.isFinite(to)) return
  // 构造临时会话项
  const temp = {
    id: to,
    name: (q.name || `用户${to}`),
    avatar: getImageUrl(q.avatar) || '/logo.jpg',
    lastMessage: '',
    lastMessageTime: '',
    unreadCount: 0,
    productId: q.productId ? Number(q.productId) : null,
    productTitle: q.productTitle || '',
    productImage: q.productImage || ''
  }
  // 如果会话列表中不存在该联系人，插入到顶部
  if (!convs.value.find(c => c.id === to)) {
    convs.value.unshift(temp)
    filterConvs()
  }
  // 选择该会话并尝试加载历史消息
  await selectConv(temp)
  // 清理一次查询参数，避免重复触发
  router.replace({ path: '/messages' })
}

const scrollToBottom = () => {
  const el = msgsRef.value
  if (el) el.scrollTop = el.scrollHeight
}

const autoResize = () => {
  const el = textareaRef.value
  if (el) {
    el.style.height = 'auto'
    el.style.height = Math.min(el.scrollHeight, 120) + 'px'
  }
}

const send = async () => {
  if (!canSend.value) return
  
  // 防止重复发送：发送时禁用按钮
  const originalContent = draft.value.trim()
  if (!originalContent) return
  
  // 立即清空输入框和禁用发送，防止重复点击
  draft.value = ''
  
  const payload = { toUserId: current.value.id, productId: current.value.productId || null, content: originalContent, type: 1 }
  try {
    const res = await post('/messages/send', payload)
    if (res && res.code === 200 && res.data) {
      // 发送成功后立即添加消息到当前会话
      const newMessage = {
        id: res.data.id || Date.now(),
        content: originalContent,
        senderId: me,
        receiverId: current.value.id,
        createdAt: new Date().toISOString(),
        type: 'text'
      }
      msgs.value.push(newMessage)
      nextTick().then(scrollToBottom)
      
      // 更新会话的最后消息信息
      current.value.lastMessage = originalContent
      current.value.lastMessageTime = newMessage.createdAt
    } else {
      const msg = res?.message || '发送失败，请稍后重试'
      console.warn('发送消息失败：', res)
      // 发送失败时恢复输入内容
      draft.value = originalContent
      // 简单提示（项目未引入全局消息组件时使用 alert）
      try { window.alert(msg) } catch {}
    }
  } catch (e) {
    console.error('发送失败', e)
    // 发送失败时恢复输入内容
    draft.value = originalContent
    try { window.alert('网络异常，发送失败') } catch {}
  }
}

const markConvRead = async (uid) => {
  try { await put(`/messages/conversation/${uid}/read`, {}) } catch (e) { console.warn('标记已读失败', e) }
}

const clearUnread = async () => {
  if (!current.value) return
  await markConvRead(current.value.id)
  // 更新本地消息状态
  msgs.value.forEach(m => {
    if (m.senderId !== me) {
      m.isUnread = false
      m.readStatus = '已读'
    }
  })
  // 更新会话未读数
  current.value.unreadCount = 0
}

const refreshMessages = async () => {
  if (!current.value) return
  await loadMsgs(current.value.id)
}

const getReadStatusText = (msg) => {
  if (msg.readStatus) return msg.readStatus
  if (msg.isRead === 0) return '未读'
  if (msg.isRead === 1) return '已读'
  return '已发送'
}

const getReadStatusClass = (msg) => {
  const status = getReadStatusText(msg)
  return {
    'status-unread': status === '未读',
    'status-read': status === '已读',
    'status-sent': status === '已发送'
  }
}

// WebSocket: 接收后端 MessageResponse 推送
let unsubMsg = null, unsubConn = null
const handlePush = (message) => {
  const m = mapMsg(message)
  // 更新会话列表（最后消息/未读计数）
  const conv = convs.value.find(x => x.id === (m.senderId===me ? m.receiverId : m.senderId))
  if (conv) {
    conv.lastMessage = m.content
    conv.lastMessageTime = m.createdAt
    if (!current.value || current.value.id !== conv.id) conv.unreadCount = (conv.unreadCount||0) + 1
    filterConvs()
  }
  // 若在当前会话，检查消息是否已存在，避免重复添加
  if (current.value && ((m.senderId === me && m.receiverId === current.value.id) || (m.senderId === current.value.id && m.receiverId === me))) {
    // 检查是否已存在相同的消息（根据时间戳和内容判断）
    const exists = msgs.value.some(existing => 
      existing.content === m.content && 
      existing.senderId === m.senderId && 
      Math.abs(new Date(existing.createdAt) - new Date(m.createdAt)) < 1000 // 1秒内的消息认为是重复的
    )
    if (!exists) {
      msgs.value.push(m)
      nextTick().then(scrollToBottom)
    }
  }
}

const handleConn = (ok) => { connStatus.value = ok ? 'connected' : 'disconnected' }

onMounted(async () => {
  await loadConvs()
  // 路由参数初始化
  await initByRoute()
  try {
    await messageService.initialize()
    unsubMsg = messageService.onMessage(handlePush)
    unsubConn = messageService.onConnectionChange(handleConn)
  } catch (e) { console.warn('WS 初始化失败', e) }
})

onUnmounted(() => {
  if (unsubMsg) unsubMsg(); if (unsubConn) unsubConn();
  try { messageService.disconnect() } catch {}
})
</script>

<style scoped>
/* ============= 全局容器 ============= */
.message-center {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  position: relative;
  overflow: hidden;
}

/* ============= 左侧对话列表 ============= */
.conversation-sidebar {
  width: 300px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #e7e7e7;
  position: relative;
  z-index: 10;
}

.sidebar-header {
  padding: 20px 16px;
  background: #ffffff;
  color: #333;
  border-bottom: 1px solid #e7e7e7;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.back-btn-icon {
  background: transparent;
  border: none;
  color: #07c160;
  padding: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.back-btn-icon svg {
  width: 20px;
  height: 20px;
}

.back-btn-icon:hover {
  background: rgba(7, 193, 96, 0.1);
  transform: translateX(-2px);
}

.title-icon {
  width: 24px;
  height: 24px;
  color: #07c160;
}

.header-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #181818;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 12px;
  width: 16px;
  height: 16px;
  color: #b2b2b2;
  pointer-events: none;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: none;
  border-radius: 4px;
  background: #f5f5f5;
  font-size: 14px;
  transition: background 0.2s;
}

.search-box input:focus {
  outline: none;
  background: #ebebeb;
}

.search-box input::placeholder {
  color: #b2b2b2;
}

/* 对话列表 */
.conversation-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.conversation-list::-webkit-scrollbar {
  width: 6px;
}

.conversation-list::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 3px;
}

.conversation-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 12px 16px;
  border: none;
  background: transparent;
  cursor: pointer;
  transition: background 0.2s;
  border-bottom: 1px solid #f5f5f5;
  text-align: left;
}

.conversation-item:hover {
  background: #f5f5f5;
}

.conversation-item.active {
  background: #ebebeb;
}

.avatar-wrapper {
  position: relative;
  flex-shrink: 0;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 6px;
  object-fit: cover;
}

.online-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  background: #07c160;
  border: 2px solid white;
  border-radius: 50%;
}

@keyframes pulse-badge {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8; }
}

.conversation-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contact-name {
  font-weight: 600;
  font-size: 15px;
  color: #1a1a1a;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.info-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.last-message {
  flex: 1;
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.last-message.unread {
  font-weight: 600;
  color: #333;
}

.unread-badge {
  background: #fa5151;
  color: white;
  font-size: 11px;
  font-weight: 500;
  padding: 1px 6px;
  border-radius: 9px;
  min-width: 18px;
  text-align: center;
  line-height: 18px;
}

/* 空状态和加载状态 */
.empty-state, .loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #b2b2b2;
  text-align: center;
}

.empty-state svg, .loading-state svg {
  width: 48px;
  height: 48px;
  margin-bottom: 12px;
  opacity: 0.3;
  color: #b2b2b2;
}

.empty-state p, .loading-state p {
  font-size: 13px;
  color: #b2b2b2;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #e0e0e0;
  border-top-color: #07c160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* ============= 右侧聊天区域 ============= */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  overflow: hidden;
}

.welcome-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #b2b2b2;
  text-align: center;
  background: #f5f5f5;
}

.welcome-screen svg {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
  opacity: 0.3;
  color: #b2b2b2;
}

.welcome-screen h3 {
  margin: 0 0 8px;
  font-size: 18px;
  font-weight: 500;
  color: #181818;
}

.welcome-screen p {
  margin: 0;
  font-size: 14px;
  color: #b2b2b2;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 聊天头部 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e7e7e7;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left .avatar-wrapper {
  position: relative;
}

.header-left .avatar {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  object-fit: cover;
}

.status-dot {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 8px;
  height: 8px;
  background: #b2b2b2;
  border: 2px solid white;
  border-radius: 50%;
}

.status-dot.online {
  background: #07c160;
}

.contact-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.contact-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #181818;
}

.contact-status {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.connection-text {
  font-size: 12px;
  color: #b2b2b2;
}

.connection-text.connected {
  color: #07c160;
}

.product-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: #576b95;
  background: #f0f4ff;
  padding: 2px 8px;
  border-radius: 3px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-tag svg {
  width: 12px;
  height: 12px;
  flex-shrink: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.icon-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 4px;
  background: transparent;
  color: #606060;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.icon-btn:hover {
  background: #f5f5f5;
}

.icon-btn svg {
  width: 18px;
  height: 18px;
}

/* 消息列表 */
.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 20px;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.messages-container::-webkit-scrollbar {
  width: 8px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 4px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #bfbfbf;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  animation: message-appear 0.3s ease-out;
}

@keyframes message-appear {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-wrapper.own {
  justify-content: flex-end;
}

.message-avatar {
  flex-shrink: 0;
}

.message-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.message-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-width: 60%;
}

.message-wrapper:not(.own) .message-group {
  align-items: flex-start;
}

.message-wrapper.own .message-group {
  align-items: flex-end;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 4px;
  background: white;
  word-wrap: break-word;
  word-break: break-word;
  line-height: 1.5;
  position: relative;
  font-size: 15px;
}

.message-wrapper.own .message-bubble {
  background: #95ec69;
  color: #181818;
}

.message-bubble.unread {
  background: #fff7e6;
  border-left: 3px solid #faad14;
  animation: highlight 2s ease-out;
}

@keyframes highlight {
  0% {
    background: #fff2e8;
    transform: scale(1.02);
  }
  100% {
    background: #fff7e6;
    transform: scale(1);
  }
}

.message-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 12px;
  display: block;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 4px;
}

.message-wrapper:not(.own) .message-info {
  justify-content: flex-start;
}

.message-wrapper.own .message-info {
  justify-content: flex-end;
}

.message-time {
  font-size: 11px;
  color: #999;
}

.read-status {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 8px;
  font-weight: 500;
}

.status-unread {
  color: #faad14;
  background: #fff7e6;
}

.status-read {
  color: #52c41a;
  background: #f6ffed;
}

.status-sent {
  color: #999;
  background: #f5f5f5;
}

/* 输入区域 */
.input-area {
  padding: 12px 16px;
  background: white;
  border-top: 1px solid #e7e7e7;
  flex-shrink: 0;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 8px 12px;
  transition: border-color 0.2s;
}

.input-wrapper:focus-within {
  border-color: #07c160;
}

.input-wrapper textarea {
  flex: 1;
  border: none;
  background: transparent;
  resize: none;
  font-size: 15px;
  line-height: 1.5;
  max-height: 100px;
  overflow-y: auto;
  font-family: inherit;
  color: #181818;
}

.input-wrapper textarea:focus {
  outline: none;
}

.input-wrapper textarea::placeholder {
  color: #b2b2b2;
}

.send-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  background: #07c160;
  color: white;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
  flex-shrink: 0;
}

.send-btn:hover:not(:disabled) {
  background: #06ad56;
}

.send-btn:active:not(:disabled) {
  background: #059048;
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: #b2b2b2;
}

.send-btn svg {
  width: 16px;
  height: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .conversation-sidebar {
    width: 100%;
    position: absolute;
    z-index: 20;
  }
  
  .chat-area {
    margin: 0;
    border-radius: 0;
  }
  
  .message-group {
    max-width: 80%;
  }
}
</style>